package com.example.modules.course.service;

import com.example.modules.course.model.TCourse;
import com.example.modules.course.repository.CourseRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: Oliver
 * @Date: 2019/2/21 11:26
 * @Description:
 */
@Service
public class CourseService {

    @Autowired
    private CourseRepository courseRepository;

    /**
     * 添加课程
     * @param course
     * @return
     */
    @Transactional
    public TCourse addCourse(TCourse course) {
        return courseRepository.save(course);
    }

    /**
     * 分页查询
     * @param pageable
     * @return
     */
    public Page<TCourse> selectPage(TCourse course, Pageable pageable) {
        return courseRepository.findAll(specification(course), pageable);
    }
    private Specification<TCourse> specification(final TCourse course) {
        return (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotEmpty(course.getCourseName())) {
                //根据登录名称模糊查询
                predicates.add(cb.like(root.get("courseName"), "%" + course.getCourseName() + "%"));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
    }

    @Transactional
    public void updateCourse(TCourse old, TCourse self) {
        BeanUtils.copyProperties(self, old); //把 self 拷贝到 old 中
        courseRepository.saveAndFlush(old);
    }

    @Transactional
    public void deleteCourse(List<Long> ids) {
        courseRepository.deleteInBatch(courseRepository.findAllById(ids));
    }

}
